<template>
    <el-dialog v-model="isOpen" title="多维聚类异常检测结果" :border="true" align-center>
        <el-descriptions column="1" border>
            <el-descriptions-item label="聚类数量">{{ result.clusterCount }}</el-descriptions-item>
            <el-descriptions-item label="噪声点数量">{{ result.noiseCount }}</el-descriptions-item>
            <el-descriptions-item label="异常点索引">
                <span v-if="result.anomalyIndices.length === 0">无异常点</span>
                <span v-else>
                    <span v-for="(index, i) in result.anomalyIndices" :key="i">
                        {{ index !== -1 ? index : "噪声点" }}{{ i < result.anomalyIndices.length - 1 ? ", " : "" }}
                    </span>
                </span>
            </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <!-- 高维数据提示 -->
        <div v-if="dimensions > 2" class="high-dim-warning" style="text-align: center; padding: 50px 0;">
            <p style="color: #666; font-size: 16px;">无法展示{{ dimensions }}维数据（仅支持2维数据可视化）</p>
        </div>

        <!-- 2维数据图表 -->
        <div v-else ref="chartContainer" style="width: 100%;height: 400px" />

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="isOpen = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from "vue"
import * as echarts             from "echarts"

let isOpen = defineModel()
let props  = defineProps([ "originalData", "result" ])

let chartContainer = ref(null)
let chartInstance  = ref(null)
let dimensions     = ref(0)  // 新增：记录数据维度

watch(isOpen, (val) => {
    if(val){
        // 计算数据维度
        dimensions.value = props.originalData?.points?.[0]?.length || 0
        // 只在2维时初始化图表
        if(dimensions.value === 2){
            initChart()
        }
    }
})

function initChart(){
    nextTick(() => {
        if(!chartContainer.value){
            return
        }
        if(!props.result){
            return
        }
        if(!props.originalData || !props.originalData.points){
            return
        }

        const points = props.originalData.points

        if(!chartInstance.value){
            chartInstance.value = echarts.init(chartContainer.value)
        }

        // 准备数据，标记异常点
        const data = points.map((point, index) => {
            const isAnomaly = props.result.anomalyIndices.includes(index) || props.result.anomalyIndices[index] === -1
            return {
                value     : point,
                itemStyle : {
                    color: isAnomaly ? "#e74c3c" : "#3498db",
                },
                symbolSize: isAnomaly ? 15 : 10,
                // 存储额外信息用于tooltip
                name        : `点 ${ index }`,
                anomalyScore: props.result.anomalyScores[index],
            }
        })

        // 图表配置（仅保留2维散点图）
        const option = {
            tooltip   : {
                trigger  : "item",
                formatter: (params) => {
                    let content = `${ params.name }<br/>`
                    params.value.forEach((val, i) => {
                        content += `维度 ${ i + 1 }: ${ val }<br/>`
                    })
                    content += `异常分数: ${ formatScore(params.data.anomalyScore) }<br/>`
                    content += `类型: ${ params.data.itemStyle.color === "#e74c3c" ? "异常点/噪声" : "正常点" }`
                    return content
                },
            },
            grid      : {
                left        : "5%",
                right       : "10%",
                bottom      : "5%",
                top         : "10%",
                containLabel: true,
            },
            xAxis     : {
                type: "value",
                name: "维度 1",
            },
            yAxis     : {
                type: "value",
                name: "维度 2",
            },
            series    : [
                {
                    type      : "scatter",
                    name      : "数据点",
                    data      : data,
                    symbolSize: 10,
                },
            ],
            annotation: {
                label: {
                    fontSize: 12,
                    color   : "#333",
                },
                data : [
                    {
                        type      : "text",
                        position  : [ "50%", "95%" ],
                        value     : `聚类数: ${ props.result.clusterCount } | 噪声数: ${ props.result.noiseCount }`,
                        xAxisIndex: 0,
                        yAxisIndex: 0,
                    },
                ],
            },
        }

        chartInstance.value.setOption(option)

        window.onresize = function(){
            chartInstance.value.resize()
        }
    })
}

// 格式化异常分数，处理极大值
function formatScore(score){
    if(score > 1e300){
        return "∞ (极大值)"
    }
    else if(score > 1e5){
        return score.toExponential(2)
    }
    else{
        return score.toFixed(4)
    }
}
</script>

<style lang="scss" scoped>
</style>

